﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DP.Web.UI;

using CRM.BLL;
using CRM.Entity;
using DP.Web.UI.Controls;
using DP.Common;
using System.Data;
using System.Text;

namespace CRM.Web.CaseManage
{
    public partial class Modify : Common.PageBase
    {
        T_FormInfo_BLL fBll = new T_FormInfo_BLL();
        T_FormFieldInfo_BLL ffBll = new T_FormFieldInfo_BLL();
        
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            if (!IsPostBack)
            {
                pageControlInit();
            }
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                pageInit();

            }


            LoadButton();
        }


        private void pageControlInit()
        {
            string formId = PageHelper.GetQueryString(this.Page, "FORMID");

            if (!String.IsNullOrEmpty(formId))
            {
                T_FormInfo_Entity entity = fBll.GetEntity("FORMID", formId);
                List<T_FormFieldInfo_Entity> list = ffBll.GetList(String.Format(" and FORMID = '{0}' ", formId), " SortNumber ASC ");
                List<WebFormField> fields = new List<WebFormField>();
                WebFormField field;
                List<string> primaryKeys = new List<string>();

                foreach (var item in list)
                {
                    field = new WebFormField();
                    field.ColSpan = StringHelper.ToInt(item.ColSpan.ToString(), 1);
                    field.CommandText = item.CommandText;
                    field.CssClass = item.CssClass;
                    field.DataSourceInfo = item.DataSourceInfo;
                    field.DataSourceType = (DataSourceType)Enum.Parse(typeof(DataSourceType), StringHelper.ToInt(item.DataSourceType.ToString(), 0).ToString());
                    field.DefaultValue = item.DefaultValue;
                    field.Description = item.FieldDescription;
                    field.ExclusiveRow = item.ExclusiveRow.ToString() == "1" ? true : false;
                    field.Fromat = item.Fromat;
                    field.Index = StringHelper.ToInt(item.SortNumber.ToString(), 1);
                    field.IsBlankRow = item.IsBlankRow.ToString() == "1" ? true : false;
                    field.IsEnabled = item.IsEnabled.ToString() == "1" ? true : false;
                    field.IsPostBack = item.IsPostBack.ToString() == "1" ? true : false;
                    field.MaxLength = StringHelper.ToInt(item.MaxLenght.ToString(), 0);
                    field.Name = item.FieldName;
                    field.RelationFields = item.RelationFields;
                    field.Type = (WebFormFieldType)Enum.Parse(typeof(WebFormFieldType), StringHelper.ToInt(item.FieldType.ToString(), 0).ToString());
                    field.Width = StringHelper.ToInt(item.Width.ToString(), 0);
                    if (item.IsPrimaryKey.ToString() == "1")
                    {
                        primaryKeys.Add(item.FieldName);
                    }
                    fields.Add(field);                    
                }
                
                if (entity != null)
                {
                    WebForm1.TableCssClass = entity.TableCssClass;
                    WebForm1.TRCssClass = entity.TRCssClass;
                    WebForm1.TDCssClass = entity.TDCssClass;
                    WebForm1.DescriptionTDCssClass = entity.DescriptionTDCssClass;
                    WebForm1.DescriptionWidth = StringHelper.ToInt(entity.DescriptionWidth.ToString(), 100);
                    WebForm1.ColumnCount = StringHelper.ToInt(entity.ColumnCount.ToString(), 1);
                    WebForm1.FieldDataSource = fields;
                    WebForm1.Title = entity.TableDescription;
                    WebForm1.PrimaryKeys = primaryKeys;
                    WebForm1.TableName = entity.TableName;
                }
                



            }
        }

        private void pageInit()
        {
            if(String.IsNullOrEmpty(WebForm1.TableName))
            {
                return;
            }
            bool isHasValue = true;
            StringBuilder sql = new StringBuilder();
            sql.AppendFormat("select * from {0} where 1=1 ", WebForm1.TableName);
            foreach (var item in WebForm1.PrimaryKeys)
            {
                if (!String.IsNullOrEmpty(item))
                {
                    sql.AppendFormat(" and {0} = '{1}' ", item, PageHelper.GetQueryString(this.Page, item));
                }
                else
                {
                    isHasValue = false;
                }
            }
            if (!isHasValue)
            {
                lblTitle.Text = WebForm1.Title + "添加";
                return;               
            }
            DataTable dt = fBll._dal.ExecuteDataAdapterSQL(sql.ToString());
            WebForm1.DataLoaded(dt);

            if (dt.Rows.Count > 0)
            {
                WebForm1.IsSuccessfullyLoadedData = true;
                lblTitle.Text = WebForm1.Title + "修改";
            }
            else
            {
                WebForm1.IsSuccessfullyLoadedData = false;
                lblTitle.Text = WebForm1.Title + "添加";
            }

        }


        /// <summary>
        /// 
        /// Loads the button.
        /// </summary>
        private void LoadButton()
        {
            Button btn = new Button();
            btn.ID = "btnOK";
            btn.CommandName = "btnOK";
            btn.Text = "OK";
            btn.CssClass = "btn";
            btn.Click += new EventHandler(btnOK_Click);
            phButton.Controls.Add(btn);
            //List<T_WORKORDEROPERATION_Entity> workOrderOperationList = workOrderOperationBll.GetList(string.Format(" and CurrentStatusID = {0} and OrderTypeID = {1} ", CaseStatus, ((int)WorkOrderType.报修工单).ToString()), " SortOrder desc, OperationID asc ");
            //foreach (var entity in workOrderOperationList)
            //{
            //    Button btn = new Button();
            //    btn.ID = StaticConstant.PreRepairCase + entity.OPERATIONID.ToString();
            //    btn.CommandName = StaticConstant.PreRepairCase + entity.OPERATIONID.ToString();
            //    btn.Text = entity.OPERATIONNAME;
            //    btn.CssClass = "btn";
            //    //if (entity.ISCONFIRM.ToString() == ((int)IsConfirm.是).ToString())
            //    //{
            //    //    btn.OnClientClick = String.Format("return confirm('您确认要执行 {0} 操作吗？');", entity.OPERATIONNAME);
            //    //}
            //    btn.Click += new EventHandler(btnOK_Click);
            //    phButton.Controls.Add(btn);
            //}
        }



         /// <summary>
        /// Handles the Click event of the btnOK control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void btnOK_Click(object sender, EventArgs e)
        {
            string message = string.Empty;
            string primaryValues = string.Empty;
            if (String.IsNullOrEmpty(WebForm1.TableName))
            {
                return;
            }
            StringBuilder sql = new StringBuilder();
            sql.AppendFormat("select * from {0} where 1=1 ", WebForm1.TableName);
            foreach (var item in WebForm1.PrimaryKeys)
            {
                if (!String.IsNullOrEmpty(item))
                {
                    sql.AppendFormat(" and {0} = '{1}' ", item, PageHelper.GetQueryString(this.Page, item));
                }
            }
            if (WebForm1.IsSuccessfullyLoadedData)
            {
                DataTable dt = fBll._dal.ExecuteDataAdapterSQL(sql.ToString());
                Dictionary<string, string> dicts = DataTableHelper.GetRow(dt, 0);
                message = WebForm1.GetFieldValues(ref dicts);
                int rel = fBll._dal.Update(WebForm1.TableName, WebForm1.PrimaryKeys.ToArray(), dicts);

            }
            else
            {
                Dictionary<string, string> dicts = new Dictionary<string, string>();
                message = WebForm1.GetFieldValues(ref dicts);

                int rel = fBll._dal.Insert(WebForm1.TableName, WebForm1.PrimaryKeys.ToArray(), DP.Data.Common.PrimaryKeyType.Auto, dicts, out primaryValues);
            }





            lblMessage.Text = message + "<br />Primarys:" + primaryValues;
            //List<FieldDataInfo> fieldList = FieldDataInfo.GetRowInfo(dt, 0);




        }



        protected void WebForm_FieldChanged(object sender, DP.Web.UI.Controls.WebFormField field, DP.Web.UI.Controls.WebFormFieldType type, string name, string value)
        {

        }


        protected List<FieldDataOptions> WebForm_DataSourceBinding(object sender, WebFormField field)
        {
            List<FieldDataOptions> list = new List<FieldDataOptions>();
            switch (field.Name)
            {
                case "BUSINESSDIVISIONID":
                    {
                        T_BUSINESSDIVISION_BLL businessDivisionBll = new T_BUSINESSDIVISION_BLL();
                        list = businessDivisionBll.GetList(String.Format(" and Status = '{0}' ", ((int)Status.启用))).Select(p => new FieldDataOptions
                        {
                            Text = p.BUSINESSDIVISIONNAME,
                            Value = p.BUSINESSDIVISIONID.ToString()
                        }).ToList();
                    }
                    break;
                case "MARKETDEPARTMENTID":
                    {
                        StringBuilder sql = new StringBuilder();
                        if (!String.IsNullOrEmpty(field.EventSourceValue))
                        {
                            sql.AppendFormat(" and {0} = '{1}' ", field.EventSource.Name, field.EventSourceValue);
                        }
                        list = CacheHelper.GetPageItem(this.Page, "MARKETDEPARTMENTID" + sql.ToString()) as List<FieldDataOptions>;
                        if (list == null)
                        {
                            T_MARKETDEPARTMENT_BLL marketDepartmentBll = new T_MARKETDEPARTMENT_BLL();
                            list = marketDepartmentBll.GetList(sql.ToString()).Select(p => new FieldDataOptions
                            {
                                Value = p.MARKETDEPARTMENTID.ToString(),
                                Text = p.MARKETDEPARTMENTNAME
                            }).ToList();
                            CacheHelper.SetPageItem(this.Page, "MARKETDEPARTMENTID" + sql.ToString(), list);
                        }

                    }
                    break;
                default:
                    {

                    }
                    break;
            }
            //list.Add(new FieldDataOptions("1", "Custom_A"));
            //list.Add(new FieldDataOptions("2", "Custom_B"));
            //list.Add(new FieldDataOptions("3", "Custom_C"));
            //list.Add(new FieldDataOptions("4", "Custom_D"));
            //list.Add(new FieldDataOptions("5", "Custom_E"));
            //list.Add(new FieldDataOptions("6", "Custom_F"));
            //lblMessage.Text += String.Format("<br />DataSourceBinding--Name:{0}", field.Name);
            return list;
        }

        protected void WebForm1_ShowMessage(object sender, string message)
        {

        }
    }
}
